package com.windea.study.springcloud.zuul.component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

//自定义zuul过滤器的示例
//@Component
public class TokenFilter extends ZuulFilter {
	private final Logger logger = LoggerFactory.getLogger(TokenFilter.class);

	@Override
	public String filterType() {
		return "pre"; // 可以在请求被路由之前调用
	}

	@Override
	public int filterOrder() {
		return 0; // filter执行顺序，通过数字指定 ,优先级为0，数字越大，优先级越低
	}

	@Override
	public boolean shouldFilter() {
		return true;// 是否执行该过滤器，此处为true，说明需要过滤
	}

	@Override
	public Object run() {
		var context = RequestContext.getCurrentContext();
		var request = context.getRequest();

		logger.info("--->>> TokenFilter {},{}", request.getMethod(), request.getRequestURL().toString());

		String token = request.getParameter("token");// 获取请求的参数

		if(!StringUtils.hasText(token)) {
			context.setSendZuulResponse(true); //对请求进行路由
			context.setResponseStatusCode(200);
			context.set("isSuccess", true);
			return null;
		} else {
			context.setSendZuulResponse(false); //不对其进行路由
			context.setResponseStatusCode(400);
			context.setResponseBody("token is empty");
			context.set("isSuccess", false);
			return null;
		}
	}

}
